package com.example.myapplication1.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.myapplication1.db.AppSqliteHelper;
import com.example.myapplication1.model.Concater;
import com.example.myapplication1.model.User;

import java.util.ArrayList;
import java.util.List;

public class ConcaterDao {
    private AppSqliteHelper helper;
    private String tableName="concater";

    public ConcaterDao(Context context){
        helper=new AppSqliteHelper(context);
    }

    //无条件查询所有联系人
    public List<Concater> queryAll(){
        List<Concater> list = null;

        SQLiteDatabase db = helper.getReadableDatabase();
        Concater bean=null;
        Cursor c= db.query(tableName,null,null,null,null,null,null,null);
        if(c!=null && c.getCount()>0){
            list=new ArrayList<>();
            while(c.moveToNext()){
                bean=new Concater();
                int Log=c.getColumnIndex("id");
                c.moveToFirst();
                int id=c.getInt(Log);
                bean.setId(id);

                Log=c.getColumnIndex("phone");
                c.moveToFirst();
                String phone=c.getString(Log);
                bean.setPhone(phone);

                Log=c.getColumnIndex("name");
                c.moveToFirst();
                String name=c.getString(Log);
                bean.setName(name);

                Log=c.getColumnIndex("pic");
                c.moveToFirst();
                String pic=c.getString(Log);
                bean.setPhone(pic);

                list.add(bean);
            }
        }

        return list;
    }

    //添加联系人到表中
    public boolean insert(Concater bean){
        SQLiteDatabase db=helper.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put("name",bean.getName());
        values.put("pic",bean.getPic());
        values.put("phone",bean.getPhone());
        long insert=db.insert(tableName,null,values);

        return insert>0;
    }

    //根据手机号查询是否存在用户
    public boolean isExistByPhone(String phone){
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor c= db.query(tableName,null,"phone=?",new String[]{phone},null,null,null,null);
        if(c!=null && c.getCount()>0){
            return c.moveToNext();
        }
        return false;
    }
}
